import { createRouter, createWebHistory } from 'vue-router'
import { ElNotification } from 'element-plus'
import ForgotPasswordView from '../views/ForgotPasswordView.vue'
import RegisterView from '../views/RegisterView.vue'

const routes = [
  {
    path: '/',
    name: 'welcome',
    component: () => import('../views/WelcomeView.vue'),
    meta: { requiresGuest: true }
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/LoginView.vue'),
    meta: { requiresGuest: true }
  },
  {
    path: '/forgot-password',
    name: 'forgot-password',
    component: ForgotPasswordView,
    meta: { requiresGuest: true, title: '重置密码' }
  },
  {
    path: '/register',
    name: 'register',
    component: RegisterView,
    meta: { requiresGuest: true, title: '注册账号' }
  },
  {
    path: '/home',
    name: 'home',
    component: () => import('@/views/HomeView.vue'),
    meta: { requiresAuth: true },
    redirect: (to) => {
      const role = localStorage.getItem('role')?.toLowerCase()
      // 根据角色重定向到不同页面
      if (role === 'admin') {
        return '/home/dashboard'
      } else if (role === 'user') {
        return '/home/flight-info'
      }
      return '/home/dashboard'
    },
    children: [
      {
        path: 'dashboard',
        name: 'dashboard',
        component: () => import('@/views/DashboardView.vue'),
        meta: { title: '首页', roles: ['admin', 'user'] }
      },
      {
        path: 'flight-info',
        name: 'flight-info',
        component: () => import('@/views/FlightInfoView.vue'),
        meta: { title: '航班信息', roles: ['admin', 'user'] }
      },
      {
        path: 'flight-time',
        name: 'flight-time',
        component: () => import('../views/FlightTimeView.vue'),
        meta: { title: '航班时间', roles: ['admin', 'user'] }
      },
      {
        path: 'airport-info',
        name: 'airport-info',
        component: () => import('../views/AirportInfoView.vue'),
        meta: { title: '机场信息', roles: ['admin'] }
      },
      {
        path: 'route-change',
        name: 'route-change',
        component: () => import('../views/RouteChangeView.vue'),
        meta: { title: '航线变更', roles: ['admin', 'user'] }
      },
      {
        path: 'route-history',
        name: 'route-history',
        component: () => import('../views/RouteHistoryView.vue'),
        meta: { title: '变更历史', roles: ['admin', 'user'] }
      },
      {
        path: 'luggage',
        name: 'luggage',
        component: () => import('../views/LuggageView.vue'),
        meta: { title: '行李管理', roles: ['admin', 'user'] }
      },
      {
        path: 'boarding-gate',
        name: 'boarding-gate',
        component: () => import('../views/BoardingGateView.vue'),
        meta: { title: '登机口管理', roles: ['admin', 'user'] }
      },
      {
        path: 'flight-states',
        name: 'flight-states',
        component: () => import('../views/FlightStatsView.vue'),
        meta: { title: '航班变更', roles: ['admin'] }
      },
      {
        path: 'account-manage',
        name: 'account-manage',
        component: () => import('../views/AccountManageView.vue'),
        meta: { title: '账号管理', roles: ['admin'] }
      },
      {
        path: 'profile',
        name: 'profile',
        component: () => import('@/views/Profile.vue'),
        meta: { title: '个人中心', roles: ['admin', 'user'] }
      }
    ]
  },
  {
    path: '/:pathMatch(.*)*',
    redirect: '/'
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  const userRole = localStorage.getItem('role')?.toLowerCase()
  const isAuthenticated = !!token
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth)
  const requiresGuest = to.matched.some(record => record.meta.requiresGuest)
  const requiredRoles = to.meta.roles?.map(r => r.toLowerCase()) || []

  // 1. 处理需要登录的页面
  if (requiresAuth) {
    if (!isAuthenticated) {
      ElNotification({
        title: '请先登录',
        message: '您需要登录才能访问该页面',
        type: 'warning'
      })
      return next('/login')
    }

    // 检查角色权限
    if (requiredRoles.length && (!userRole || !requiredRoles.includes(userRole))) {
      ElNotification({
        title: '权限不足',
        message: '您没有访问该页面的权限',
        type: 'error'
      })
      return next(from.fullPath || '/home/dashboard')
    }
  }

  // 2. 处理需要未登录的页面（如登录、注册页）
  if (requiresGuest && isAuthenticated) {
    ElNotification({
      title: '已登录',
      message: '您已登录，请先退出登录',
      type: 'warning'
    })
    return next('/home/dashboard')
  }

  // 3. 设置页面标题
  if (to.meta.title) {
    document.title = `${to.meta.title} - 航班管理系统`
  }

  next()
})
export default router
